package com.zfei.gfb.core;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.MessageConstraints;

import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;

/**
 * @author fgh
 */
public class HttpConf {

    private ConnectionConfig connectionConfig = ConnectionConfig.DEFAULT;

    private RequestConfig requestConfig = RequestConfig.DEFAULT;

    private int maxConnTotal = 2000;

    private int maxConnPerRoute = 1000;

    public HttpConf() {
    }

    public HttpConf(ConnectionConfig connectionConfig, RequestConfig requestConfig) {
        this.connectionConfig = connectionConfig;
        this.requestConfig = requestConfig;
    }

    public HttpConf(ConnectionConfig connectionConfig, RequestConfig requestConfig, int maxConnTotal, int maxConnPerRoute) {
        this.connectionConfig = connectionConfig;
        this.requestConfig = requestConfig;
        this.maxConnTotal = maxConnTotal;
        this.maxConnPerRoute = maxConnPerRoute;
    }

    public ConnectionConfig getConnectionConfig() {
        return connectionConfig;
    }

    public void setConnectionConfig(ConnectionConfig connectionConfig) {
        this.connectionConfig = connectionConfig;
    }

    public RequestConfig getRequestConfig() {
        return requestConfig;
    }

    public void setRequestConfig(RequestConfig requestConfig) {
        this.requestConfig = requestConfig;
    }

    public int getMaxConnTotal() {
        return maxConnTotal;
    }

    public void setMaxConnTotal(int maxConnTotal) {
        this.maxConnTotal = maxConnTotal;
    }

    public int getMaxConnPerRoute() {
        return maxConnPerRoute;
    }

    public void setMaxConnPerRoute(int maxConnPerRoute) {
        this.maxConnPerRoute = maxConnPerRoute;
    }

    public static HttpConf create() {
        return new HttpConf(ConnectionConfig.custom()
                .setMalformedInputAction(CodingErrorAction.IGNORE)
                .setUnmappableInputAction(CodingErrorAction.IGNORE)
                .setCharset(StandardCharsets.UTF_8)
                .setMessageConstraints(MessageConstraints.custom()
                        .setMaxHeaderCount(Conf.getInteger("HttpClientMaxHeaderCount", 200))
                        .setMaxLineLength(Conf.getInteger("HttpClientMaxLineLength", 2000))
                        .build())
                .build(),
                RequestConfig.custom()
                        .setSocketTimeout(Conf.getInteger("HttpClientSocketTimeout", 5000))
                        .setConnectTimeout(Conf.getInteger("HttpClientConnectTimeout", 5000))
                        .setConnectionRequestTimeout(Conf.getInteger("HttpClientConnectionRequestTimeout", 5000))
                        .build(),
                Conf.getInteger("HttpClientMaxConnTotal", 2000),
                Conf.getInteger("HttpClientMaxConnPerRoute", 1000));
    }
}
